package com.xxx.mylibrary

import android.app.Application
import android.content.Context
import android.net.ConnectivityManager
import com.qsinong.qlog.QLog
import com.qsinong.qlog.QLogConfig
import java.security.SecureRandom
import javax.net.ssl.HttpsURLConnection
import javax.net.ssl.SSLContext
import javax.net.ssl.TrustManager
import javax.net.ssl.X509TrustManager

open class App : Application() {
    override fun onCreate() {
        super.onCreate()
        instance = this
        handleSSL()
        initQLog()
    }

    private fun initQLog() {
        QLog.init(
            QLogConfig.Build(this)
                .path(getExternalFilesDir(null).toString() + "/QLog") //日志目录,一般不要动安卓10限制了外部目录访问了
                .buffSize(128 * 1024) //buff大小
                .delay(10000) //延迟写入时间
                .day(30) //日志保留30天,默认无限制
                .methodCount(1) //打印调用方法名
                .debug(BuildConfig.DEBUG) //true会输出控制台,上线可关掉
                .logFormat { level, time, log, stact ->
                    //自定义日记格式
                    "$level $time $log ~$stact"
                }
                .writeData { folder, fileName, bytes ->
                    //写入拦截,可自定义写入/上传操作
                    false //false会继续执行写入, true不继续执行
                }
                .build())
        QLog.i("initQLog success")
    }

    private fun handleSSL() {
        try {
            val trustAllCerts: Array<TrustManager> =
                arrayOf<TrustManager>(object : X509TrustManager {
                    override fun checkClientTrusted(
                        chain: Array<out java.security.cert.X509Certificate>?,
                        authType: String?
                    ) {

                    }

                    override fun checkServerTrusted(
                        chain: Array<out java.security.cert.X509Certificate>?,
                        authType: String?
                    ) {
                    }

                    override fun getAcceptedIssuers(): Array<java.security.cert.X509Certificate> {
                        return arrayOf()
                    }

                })
            val sc: SSLContext = SSLContext.getInstance("TLS")
            // trustAllCerts信任所有的证书
            sc.init(null, trustAllCerts, SecureRandom())
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.socketFactory)
            HttpsURLConnection.setDefaultHostnameVerifier { _, _ -> true }
        } catch (ignored: Exception) {
        }
    }

    companion object {
        lateinit var instance: Application
        fun isNetworkConnected(): Boolean {
            val mConnectivityManager = instance
                .getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
            val mNetworkInfo = mConnectivityManager.activeNetworkInfo
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable
            }
            return false
        }
    }
}